import React, { useEffect } from "react"
import GpContainer from "@/components/GpContainer"
import { Image, View } from "@tarojs/components"
import styles from "./index.module.scss"
import Icon from "@/components/GpFontIcon"
import Taro, { usePullDownRefresh, useReachBottom } from "@tarojs/taro"
import { useSetState } from "@/utils/hooks"
import { deleteMyReply, getMyReply } from "@/apis/yikao-community"
import { requestIsFullfilled } from "@/utils/request"
import { ContentNoteAttachmentType, ReplyNoticeStatus, ReplyNoticeType } from "@/types/enum"
import { navigation } from "@/utils/router"
import { pageMapperCommunity } from "@/constants/pageMap"
import GpEmpty from "@/components/GpEmpty"

type IState = {
  list: IApiRelative.IGetMyReply.IGetMyReplyItem[]
  hasMore: boolean
  current: number
}
/**
 * @page 我的回复
 */
export default function MyReply() {
  const [state, setState, stateRef] = useSetState<IState>(
    {
      list: [],
      hasMore: true,
      current: 1
    },
    true
  )
  useEffect(() => {
    fetchReplies()
  }, [])
  usePullDownRefresh(() => {
    setState({
      current: 1,
      hasMore: true
    })
    fetchReplies()
    Taro.stopPullDownRefresh()
  })
  useReachBottom(() => {
    if (stateRef.current!.hasMore) {
      setState({
        current: stateRef.current!.current + 1
      })
      fetchReplies()
    }
  })
  function fetchReplies() {
    Taro.showLoading({
      title: "加载中"
    })
    getMyReply({
      pagination: {
        current: stateRef.current!.current,
        pageSize: 10
      },
      search: {},
      sort: {
        predicate: "",
        reverse: false
      }
    })
      .then(res => {
        if (requestIsFullfilled(res)) {
          const { list, pagination } = res.data.data
          setState({
            list: pagination.current === 1 ? list : [...stateRef.current!.list, ...list],
            hasMore: pagination.current < pagination.pageCount
          })
        }
        Taro.hideLoading()
      })
      .catch(() => {
        Taro.hideLoading()
      })
  }
  function handleRemoveReply(replyId: number) {
    Taro.showModal({
      title: "提示",
      content: "确定要删除这条回复吗？",
      success: ({ confirm }) => {
        if (confirm) {
          deleteMyReply({ id: replyId }).then(res => {
            if (requestIsFullfilled(res)) {
              Taro.showToast({
                title: "删除成功"
              })
              const _list = stateRef.current!.list.filter(l => l.id !== replyId)
              setState({
                list: _list
              })
            }
          })
        }
      }
    })
  }
  function handleClickRelate(relate: IApiRelative.IGetMyReply.IGetMyReplyItem) {
    if (relate.relationNoteFileType === ContentNoteAttachmentType.Video) {
      navigation(pageMapperCommunity.VideoNoteDetail, { id: relate.relationNoteId })
    } else {
      navigation(pageMapperCommunity.NoteDetail, { id: relate.relationNoteId })
    }
  }
  function renderEmpty() {
    return (
      <GpEmpty
        imageProps={{
          src: "https://static.91goodschool.com/UpFiles/public/yikao/image/xiaoxi.png",
          style: {
            width: 126,
            height: 112
          }
        }}
        emptyProps={{
          style: {
            paddingTop: 120
          }
        }}
        description="还没有用户回复你哦"
      />
    )
  }
  return (
    <GpContainer className="min-h-screen">
      <View className={styles.list}>
        {state.list.length > 0
          ? state.list.map(l => {
              let label = ""
              let isShort = false
              if (l.relationType === ReplyNoticeType.VisitorReply) {
                label = "回复了你的评论"
              } else if (l.relationType === ReplyNoticeType.NoteComment) {
                label = "评论了我的笔记"
              } else if (l.relationType === ReplyNoticeType.NoteCommentShort) {
                label = "评论了我的短评"
                isShort = true
              }
              return (
                <View className={styles.item} key={l.id}>
                  <View className="flex flex-row items-center box-border">
                    <View
                      className="flex flex-row items-center box-border"
                      onClick={() =>
                        navigation(pageMapperCommunity.PersonalPage, { id: l.sourceMiniVisitorId })
                      }
                    >
                      <Image
                        src={l.sourceMiniVisitorHead || process.env.__DEF_AVATAR__}
                        className="w-64px h-64px object-cover rounded-full mr-8px"
                      />
                      <View className="flex flex-col justify-center">
                        <View className="flex flex-row items-center">
                          <View className="text-bold text-32px font-500">
                            {l.sourceMiniVisitorName}
                          </View>
                          {l.status === ReplyNoticeStatus.Unread && (
                            <View className={styles.UnknownFlag}>新</View>
                          )}
                        </View>
                        <View className="text-light text-24px mt-4px">{l.updatedRelativeTime}</View>
                      </View>
                    </View>
                    <Icon
                      icon="icon-youjiancaidan-shanchu"
                      size={28}
                      className="flex-none ml-auto"
                      color="#BBBBBB"
                      onClick={() => handleRemoveReply(l.id)}
                    />
                  </View>
                  <View className="mt-34px text-28px leading-36px">
                    <View className="inline text-light">{label}：</View>
                    <View className="inline text-bold">{l.content}</View>
                  </View>
                  <View className={styles.relate} onClick={() => handleClickRelate(l)}>
                    {!isShort && l.relationImage && (
                      <Image
                        src={l.relationImage}
                        className="w-80px h-80px object-cover flex-none mr-16px"
                      />
                    )}
                    <View className="flex flex-col justify-center flex-1 w-0">
                      <View className="truncate text-bold text-28px font-500">
                        {l.relationTitle}
                      </View>
                      <View className="flex flex-row items-center mt-16px">
                        <Image
                          src={l.relationMiniVisitorHead || process.env.__DEF_AVATAR__}
                          className="w-24px h-24px rounded-full object-cover mr-8px"
                        />
                        <View className="text-light text-24px">{l.relationMiniVisitorName}</View>
                      </View>
                    </View>
                  </View>
                </View>
              )
            })
          : renderEmpty()}
      </View>
    </GpContainer>
  )
}
